<?php

namespace common\models\school;

use Yii;
use common\models\user\UserFollow;

/**
 * This is the model class for table "{{%school}}".
 *
 * @property int $id
 * @property string $number 学校编号
 * @property string $name 学校名称
 * @property string $cover 学校展示封面
 * @property string $province 省份
 * @property string $city 市
 * @property string $district 区
 * @property string $region 地区
 * @property string $address_detail 详细地址
 * @property string $telephone 客服电话
 * @property int $grade 认证等级
 * @property int $president_id 校长ID
 * @property int $status 状态
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 */
class School extends \common\base\ActiveRecord {

    use \common\traits\Constants;
    use \common\traits\TimestampBehavior;

    const STATUS_ACTIVE = 10;
    const STATUS_DEFAULT = 0;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%school}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['number', 'name', 'cover', 'province', 'city', 'address_detail', 'telephone'], 'required'],
            [['grade', 'president_id', 'status', 'created_at', 'updated_at'], 'integer'],
            [['number'], 'string', 'max' => 32],
            [['name'], 'string', 'max' => 50],
            [['province', 'city', 'district'], 'string', 'max' => 6],
            [['cover', 'region', 'address_detail'], 'string', 'max' => 255],
            [['telephone'], 'string', 'max' => 100],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'number' => '学校编号',
            'name' => '学校名称',
            'cover' => '学校展示封面',
            'province' => '省份',
            'city' => '市',
            'district' => '区',
            'region' => '地区',
            'address_detail' => '详细地址',
            'telephone' => '客服电话',
            'grade' => '认证等级',
            'president_id' => '校长ID',
            'status' => '状态',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    public function getData() {
        return $this->hasOne(SchoolData::className(), ['school_id' => 'id']);
    }

    public function getFollow() {
        return $this->hasOne(UserFollow::className(), ['model_id' => 'id'])->andWhere([
            'model' => UserFollow::MODEL_SCHOOL,
        ]);
    }

    public function getFollowed() {
        return $this->getFollow()->andWhere(['user_id' => Yii::$app->user->id])->exists();
    }

}
